package net.seehope.foodie.controller.advice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpRequest;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.seehope.foodie.common.JsonResult;

/*
 *增强的Controller,可以捕获控制器当中的异常
 *1.全局异常处理
 *2.全局数据绑定
 *3.全局数据预处理 
 */

@ControllerAdvice
public class ControllerExceptionHandler {
	//控制器中发生的所有异常都会被这个方法捕获到
	@ExceptionHandler(value = Exception.class)
	@ResponseBody
	public JsonResult defaultExceptionHandler(HttpServletRequest req,HttpServletResponse res,Exception e) {
		e.printStackTrace();
		return JsonResult.errorMsg(e.getLocalizedMessage());
	}
	
	
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public JsonResult handleMethodArgumentNotValidException(HttpServletRequest req, HttpServletResponse resp,
			MethodArgumentNotValidException e) throws JsonProcessingException{
			
		Map<String, String> errorMsg = new HashMap<String, String>();
		
		List<FieldError> fieldsList = e.getBindingResult().getFieldErrors();
		for (FieldError fieldError : fieldsList) {
			errorMsg.put(fieldError.getField(), fieldError.getDefaultMessage());
		}

		/*
		 * e.getBindingResult().getFieldErrors().forEach(fieldError -> {
		 * System.out.println(fieldError.getField() + ":" +
		 * fieldError.getDefaultMessage()); });
		 */	
		
		return JsonResult.errorMsg(new ObjectMapper().writeValueAsString(errorMsg));
	}
	
	

}
